import time
from wxauto import WeChat

from chatbot.messageList import MessageContent
from chatbot.wechatResponser import WechatResponser

class WechatBot:
    def __init__(self, tools):
        # 初始化 FunctionResponser 对象。
        # tools: AI可以调用的方法库

        self.controller = "文件传输助手"
        self.aiDic = {}
        self.tools = tools
        try:
            self.wx = WeChat()
        except:
            print('微信未登陆')

    def run_listen(self):
        

        try:
            self.wx.AddListenChat(self.controller)
        except:
            print(f'监听{self.controller}失败!')
        
        listen_flag = True
        while listen_flag:
            msgs = self.wx.GetListenMessage()
            for chat in msgs:
                messageList = msgs.get(chat)
                
                for msg in messageList:
                    print(f"收到窗口{chat.who} {msg.sender} {msg.type}的消息: {msg.content}")
                    if msg.type != 'self' and msg.type != 'friend':
                        continue
                    if chat.who == self.controller and msg.sender == 'Self': 
                        listen_flag = self.response_control(msg.content)
                    # 排除掉我跟我自己AI聊天的情况 需要用是否为自己来判断
                    elif chat.who == self.wx.nickname:
                        ai = self.aiDic.get(chat.who)
                        if ai != None and msg.content != ai.speak():
                            aiResponse = ai.next(msg.content).speak()
                            self.speak_to(aiResponse, chat.who)
                    else:
                        if msg.type == 'self':
                            ai = self.aiDic.get(chat.who)
                            if ai != None: ai.add_message(msg.content)
                        else:
                            ai = self.aiDic[chat.who]
                            if ai != None: 
                                aiResponse = ai.next(msg.content).speak()
                                self.speak_to(aiResponse, chat.who)

            time.sleep(1)

    def response_control(self, content):
        commandList = ['指令', '结束监听', '结束监听 <人名>', 'ai聊天 <人名> <设定>']
        commandDescription = f'现在的控制指令有：{commandList}'
        #先检查是否是程序控制
        if content == "指令":
            self.speak_to_controller(commandDescription)
        elif str(content).startswith('结束监听'):
            if content == '结束监听':
                return False
            name = str(content).split(' ')[1]
            self.aiDic.pop(name)
            self.speak_to_controller(f'结束{name}的ai聊天成功')
        elif str(content).startswith('ai聊天'):
            param = str(content).split(' ')
            try:
                self.wx.AddListenChat(param[1])
                self.aiDic[param[1]] = WechatResponser(self.tools, param[2] if len(param) > 2 else None)
                self.speak_to_controller(f'创建{param[1]}的ai聊天成功')
            except:
                self.speak_to_controller(f'创建{param[1]}的ai聊天失败')
        
        return True
            

    def speak_to(self, content, target):
        # 发送内容
        self.wx.SendMsg(msg=content, who=target)

    def speak_to_controller(self, content):
        self.wx.SendMsg(msg=content, who=self.controller)